<template>
    <view class="dynamic-details-page">
        <!-- 导航栏组件 -->
        <navbar-component title="动态详情" @goBack="goBack" />

        <!-- 页面内容 -->
        <view class="dynamic-details-content">
            <!-- 加载状态 -->
            <view v-if="loading" class="loading-container">
                <text class="loading-text">数据加载中...</text>
            </view>

            <!-- 帖子卡片 -->
            <dynamic-details-user-context
                v-else
                :dynamic-data="dynamicData"
                :comments-count="commentsList.length"
                :like-count="getEssayLikeCount()"
                :is-liked="isEssayLiked"
                @like-click="toggleEssayLike"
            />

            <!-- 评论区域 -->
            <dynamic-details-comments
                :comments-list="commentsList"
                @like-click="toggleLike"
                @delete-comment="deleteComment"
            />

            <!-- 底部操作栏 -->
            <view class="bottom-bar">
                <view class="share-button">
                    <text class="share-icon">↗</text>
                    <text class="share-text">分享</text>
                </view>
                <view class="input-section">
                    <input class="comment-input" placeholder="请输入评论内容" v-model="commentText" />
                </view>
                <view class="action-buttons">
                    <button 
                        class="send-btn" 
                        :class="{ 'disabled': !commentText.trim() }"
                        :disabled="!commentText.trim()"
                        @click="sendComment"
                    >
                        发送
                    </button>
                </view>
            </view>
        </view>
    </view>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import NavbarComponent from '../../zujian/navbar.vue';
import DynamicDetailsUserContext from '../../zujian/dynamic_details_user_context.vue';
import DynamicDetailsComments from '../../zujian/dynamic_details_comments.vue';
import axios from 'axios';

export default {
    name: 'DynamicDetails',
    components: {
        NavbarComponent,
        DynamicDetailsUserContext,
        DynamicDetailsComments
    },
    setup() {
        // 响应式数据
        const commentText = ref('');
        const dynamicData = ref({});
        const loading = ref(true);
        const commentsList = ref([]);
        const viewsUpdated = ref(false);
        const essayLiked = ref(false);
        const essayLikeCount = ref(0);

        // 计算属性
        const isEssayLiked = computed(() => {
            return essayLiked.value;
        });

        // 获取动态数据
        const getDynamicData = () => {
            loading.value = true;
            
            // 从页面参数中获取动态ID
            const pages = getCurrentPages();
            const currentPage = pages[pages.length - 1];
            const dynamicId = currentPage.options?.dynamicId;
            
            console.log('获取到的动态ID:', dynamicId);
            
            if (!dynamicId) {
                console.error('未获取到动态ID');
                                 dynamicData.value = {
                     author: { name: '系统用户' },
                     createdata: new Date().toLocaleString(),
                     context: '动态ID不存在',
                     topic: ['错误'],
                     views: 0,
                     comments: 0,
                     likes: [],
                     anonymity: false
                 };
                loading.value = false;
                return;
            }
            
            // 获取所有动态数据，然后找到对应的动态
            axios.get('/h5api/ltc/essay').then(res => {
                if (res.data && res.data.data && res.data.data.length > 0) {
                    // 根据dynamicId找到对应的动态
                    const targetDynamic = res.data.data.find(item => item._id === dynamicId);
                    
                    if (targetDynamic) {
                        console.log('找到目标动态:', targetDynamic);
                        dynamicData.value = targetDynamic;
                        initializeEssayLikeStatus();
                        getComments();
                        updateViews();
                    } else {
                        console.error('未找到对应的动态数据');
                                                 dynamicData.value = {
                             author: { name: '系统用户' },
                             createdata: new Date().toLocaleString(),
                             context: '动态不存在',
                             topic: ['错误'],
                             views: 0,
                             comments: 0,
                             likes: [],
                             anonymity: false
                         };
                    }
                } else {
                    console.error('获取动态列表失败');
                                         dynamicData.value = {
                         author: { name: '系统用户' },
                         createdata: new Date().toLocaleString(),
                         context: '暂无动态内容',
                         topic: ['默认标签'],
                         views: 0,
                         comments: 0,
                         likes: [],
                         anonymity: false
                     };
                }
                loading.value = false;
            }).catch(error => {
                console.error('获取动态数据失败:', error);
                                 dynamicData.value = {
                     author: { name: '系统用户' },
                     createdata: new Date().toLocaleString(),
                     context: '数据加载失败',
                     topic: ['错误'],
                     views: 0,
                     comments: 0,
                     likes: [],
                     anonymity: false
                 };
                loading.value = false;
            });
        };

        // 格式化日期
        const formatDate = (date) => {
            if (!date) return new Date().toLocaleString();
            if (typeof date === 'string') {
                return new Date(date).toLocaleString();
            }
            if (date instanceof Date) {
                return date.toLocaleString();
            }
            return new Date().toLocaleString();
        };



        // 返回上一级页面
        const goBack = () => {
            uni.navigateBack();
        };

        // 发送评论
        const sendComment = () => {
            if (!commentText.value.trim()) {
                uni.showToast({
                    title: '评论内容不能为空',
                    icon: 'none'
                });
                return;
            }

            uni.showLoading({
                title: '发送中...'
            });

            const commentData = {
                content: commentText.value.trim(),
                essayId: dynamicData.value._id || dynamicData.value.id,
                author: {
                    _id: '689af77e90a9f6f3966d389d',
                    name: '静'
                },
                like: 0,
                parentId: null,
                replyTo: null
            };

            axios.post('/h5api/ltc/comments/add', commentData)
                .then(res => {
                    uni.hideLoading();
                    if (res.data && res.data.code === 200) {
                        // 更新前端显示的评论数
                        dynamicData.value.comments = (dynamicData.value.comments || 0) + 1;
                        commentText.value = '';
                        uni.showToast({
                            title: '评论成功',
                            icon: 'success'
                        });
                        // 重新获取评论列表以确保数据同步
                        getComments();
                        // 重新获取动态数据以更新评论数
                        axios.get('/h5api/ltc/essay').then(res => {
                            if (res.data && res.data.data && res.data.data.length > 0) {
                                const updatedEssay = res.data.data.find(essay => 
                                    essay._id === dynamicData.value._id || essay.id === dynamicData.value.id
                                );
                                if (updatedEssay) {
                                    dynamicData.value.comments = updatedEssay.comments;
                                }
                            }
                        }).catch(error => {
                            console.error('更新评论数失败:', error);
                        });
                    } else {
                        uni.showToast({
                            title: res.data?.msg || '评论失败',
                            icon: 'none'
                        });
                    }
                })
                .catch(error => {
                    uni.hideLoading();
                    console.error('发送评论失败:', error);
                    uni.showToast({
                        title: '网络错误，请重试',
                        icon: 'none'
                    });
                });
        };

        // 更新浏览量
        const updateViews = () => {
            if (viewsUpdated.value) {
                return;
            }
            
            const essayId = dynamicData.value._id || dynamicData.value.id;
            if (!essayId) {
                return;
            }
            
            if (!dynamicData.value.context && !dynamicData.value.author) {
                return;
            }
            
            viewsUpdated.value = true;
            
            axios.post('/h5api/ltc/updateViews', {
                essayId: essayId
            }).then(res => {
                if (res.data && res.data.code === 200) {
                    dynamicData.value.views = res.data.data.views;
                } else {
                    viewsUpdated.value = false;
                }
            }).catch(error => {
                console.error('浏览量更新请求失败:', error);
                viewsUpdated.value = false;
            });
        };

        // 获取评论列表
        const getComments = () => {
            axios.get(`/h5api/ltc/comments/list?essayId=${dynamicData.value._id || dynamicData.value.id}`)
                .then(res => {
                    if (res.data && res.data.code === 200) {
                        // 确保每个评论的 like 字段都是数组格式
                        const comments = res.data.data || [];
                        comments.forEach(comment => {
                            if (!comment.like || !Array.isArray(comment.like)) {
                                comment.like = [];
                            }
                        });
                        commentsList.value = comments;
                    } else {
                        commentsList.value = [];
                        uni.showToast({
                            title: res.data?.msg || '获取评论失败',
                            icon: 'none'
                        });
                    }
                })
                .catch(error => {
                    console.error('获取评论失败:', error);
                    commentsList.value = [];
                    uni.showToast({
                        title: '网络错误，请重试',
                        icon: 'none'
                    });
                });
        };

        // 点赞/取消点赞
        const toggleLike = (comment) => {
            const userId = '689af77e90a9f6f3966d389d';
            
            uni.showLoading({
                title: '处理中...'
            });
            
            axios.post('/h5api/ltc/comments/like', {
                commentId: comment._id,
                userId: userId
            }).then(res => {
                uni.hideLoading();
                
                if (res.data && res.data.code === 200) {
                    // 确保 comment.like 是数组格式
                    if (res.data.data.likeCount && Array.isArray(res.data.data.likeCount)) {
                        comment.like = res.data.data.likeCount;
                    } else {
                        // 如果返回的不是数组，初始化为空数组
                        comment.like = [];
                    }
                    
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'success'
                    });
                    
                    getComments();
                } else {
                    uni.showToast({
                        title: res.data?.msg || '操作失败',
                        icon: 'none'
                    });
                }
            }).catch(error => {
                uni.hideLoading();
                console.error('点赞操作失败:', error);
                uni.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
            });
        };



        // 文章点赞/取消点赞
        const toggleEssayLike = () => {
            const essayId = dynamicData.value._id || dynamicData.value.id;
            const userId = '689af77e90a9f6f3966d389d';
            
            if (!essayId) {
                uni.showToast({
                    title: '文章ID不存在',
                    icon: 'none'
                });
                return;
            }

            uni.showLoading({
                title: '处理中...'
            });

            axios.post('/h5api/ltc/essay/like', {
                essayId: essayId,
                userId: userId
            }).then(res => {
                uni.hideLoading();
                
                if (res.data && res.data.code === 200) {
                    essayLiked.value = res.data.data.isLiked;
                    essayLikeCount.value = res.data.data.likeCount;
                    
                    uni.showToast({
                        title: res.data.msg,
                        icon: 'success'
                    });
                    
                    getDynamicData();
                } else {
                    uni.showToast({
                        title: res.data?.msg || '操作失败',
                        icon: 'none'
                    });
                }
            }).catch(error => {
                uni.hideLoading();
                console.error('文章点赞操作失败:', error);
                uni.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
            });
        };

        // 获取文章点赞数量
        const getEssayLikeCount = () => {
            return essayLikeCount.value || 0;
        };

        // 删除评论
        const deleteComment = (comment) => {
            // 验证评论数据
            if (!comment || !comment._id) {
                uni.showToast({
                    title: '评论数据异常',
                    icon: 'none'
                });
                return;
            }

            // 验证文章ID
            const essayId = dynamicData.value._id || dynamicData.value.id;
            if (!essayId) {
                uni.showToast({
                    title: '文章数据异常',
                    icon: 'none'
                });
                return;
            }

            uni.showLoading({
                title: '删除中...'
            });

            axios.post('/h5api/ltc/comments/delete', {
                commentId: comment._id,
                essayId: essayId
            }).then(res => {
                uni.hideLoading();
                
                if (res.data && res.data.code === 200) {
                    // 从评论列表中移除该评论
                    const index = commentsList.value.findIndex(c => c._id === comment._id);
                    if (index > -1) {
                        commentsList.value.splice(index, 1);
                    }
                    
                    // 更新文章评论数
                    dynamicData.value.comments = Math.max(0, (dynamicData.value.comments || 0) - 1);
                    
                    uni.showToast({
                        title: '删除成功',
                        icon: 'success'
                    });
                    
                    // 重置删除状态
                    setTimeout(() => {
                        // 通过重新获取评论列表来重置删除状态
                        getComments();
                    }, 100);
                } else {
                    uni.showToast({
                        title: res.data?.msg || '删除失败',
                        icon: 'none'
                    });
                }
                
                // 重置删除状态
                setTimeout(() => {
                    getComments();
                }, 100);
            }).catch(error => {
                uni.hideLoading();
                console.error('删除评论失败:', error);
                uni.showToast({
                    title: '网络错误，请重试',
                    icon: 'none'
                });
                
                // 重置删除状态
                setTimeout(() => {
                    getComments();
                }, 100);
            });
        };

        // 初始化文章点赞状态和数量
        const initializeEssayLikeStatus = () => {
            const essayId = dynamicData.value._id || dynamicData.value.id;
            const userId = '689af77e90a9f6f3966d389d';
            
            if (!essayId) {
                essayLiked.value = false;
                essayLikeCount.value = 0;
                return;
            }

            axios.get(`/h5api/ltc/essay/likeStatus?essayId=${essayId}&userId=${userId}`)
                .then(res => {
                    if (res.data && res.data.code === 200) {
                        essayLiked.value = res.data.data.isLiked;
                        essayLikeCount.value = res.data.data.likeCount;
                    } else {
                        essayLiked.value = false;
                        essayLikeCount.value = 0;
                    }
                })
                .catch(error => {
                    console.error('获取文章点赞状态请求失败:', error);
                    essayLiked.value = false;
                    essayLikeCount.value = 0;
                });
        };

        // 生命周期
        onMounted(() => {
            viewsUpdated.value = false;
            getDynamicData();
        });

        return {
            // 响应式数据
            commentText,
            dynamicData,
            loading,
            commentsList,
            viewsUpdated,
            essayLiked,
            essayLikeCount,
            
            // 计算属性
            isEssayLiked,
            
            // 方法
            getDynamicData,
            formatDate,
            goBack,
            sendComment,
            updateViews,
            getComments,
            toggleLike,
            toggleEssayLike,
            getEssayLikeCount,
            initializeEssayLikeStatus,
            deleteComment
        };
    }
}
</script>

<style lang="scss" scoped>
.dynamic-details-page {
    width: 100%;
    min-height: calc(100vh - 100px);
    padding-bottom: 50px;
    background-color: #f5f5f5;
}

.dynamic-details-content {
    padding: 15px;
    height: 100%;
}

/* 加载状态样式 */
.loading-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 200px;
    background-color: #ffffff;
    border-radius: 12px;
    margin-bottom: 15px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.loading-text {
    font-size: 16px;
    color: #666;
}





/* 底部操作栏 */
.bottom-bar {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #ffffff;
    padding: 15px;
    border-top: 1px solid #eee;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.share-button {
    display: flex;
    align-items: center;
    padding: 8px 12px;
}

.share-icon {
    font-size: 16px;
    margin-right: 4px;
}

.share-text {
    font-size: 14px;
    color: #333;
}

.input-section {
    flex: 1;
    margin: 0 15px;
}

.comment-input {
    width: 100%;
    background-color: #f8f9fa;
    border: 1px solid #e9ecef;
    border-radius: 20px;
    padding: 5px 10px;
    font-size: 14px;
    color: #333;
    height: 40px;
}

.action-buttons {
    display: flex;
    gap: 8px;
}

.virtual-send-btn,
.send-btn {
    background-color: #ff4757;
    color: #ffffff;
    border: none;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
}

.virtual-send-btn {
    background-color: #ff6b6b;
}

.send-btn {
    background-color: #ff4757;
    color: #ffffff;
    border: none;
    padding: 8px 12px;
    border-radius: 6px;
    font-size: 12px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
}

.send-btn.disabled {
    background-color: #ccc;
    color: #999;
    cursor: not-allowed;
    opacity: 0.6;
}
</style>